<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="用户管理" />
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button @click="openCreateDrawer" type="primary">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>
        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>
    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" title="新建">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="账户" path="username">
          <n-input placeholder="请输入名称" v-model:value="formParams.username" />
        </n-form-item>
        <n-form-item label="手机号" path="phone">
          <n-input type="text" placeholder="请输入手机号" v-model:value="formParams.phone" />
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input type="password" placeholder="请输入密码" v-model:value="formParams.password" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h } from 'vue';
  import { FormRules, useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { fetchList, delObj } from '@/api/system/user';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  const message = useMessage();
  const actionRef = ref();
  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formRef: any = ref(null);
  const params = reactive({
    page: 1,
    pageSize: 5,
    username: null,
    phone: null,
  });
  const formParams = reactive({
    username: '',
    phone: '',
    password: '',
  });
  function openCreateDrawer() {
    showModal.value = true;
  }
  const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
              return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['system_user'],
          },
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            auth: ['system_user'],
          },
        ],
        dropDownActions: [
          {
            label: '启用',
            key: 'enabled',
            // 根据业务控制是否显示: 非enable状态的不显示启用按钮
            ifShow: () => {
              return true;
            },
          },
          {
            label: '禁用',
            key: 'disabled',
            ifShow: () => {
              return true;
            },
          },
        ],
      });
    },
  });

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };
    return await fetchList(_params);
  };

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }
  function reloadTable() {
    actionRef.value.reload();
  }

  function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    showModal.value = true;
    //router.push({ name: 'basic-info', params: { id: record.id } });
  }

  async function handleDelete(record: Recordable) {
    //console.log('点击了删除', record);
    await delObj(record.id);
    message.info('删除成功');
    reloadTable();
  }
  const rules: FormRules = {
    username: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入账户',
    },
    phone: {
      type: 'number',
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入手机号',
    },
    password: {
      required: true,
      trigger: ['blur', 'change'],
      message: '请输入密码',
    },
  };
  const schemas: FormSchema[] = [
    {
      field: 'username',
      labelMessage: '这是一个提示',
      component: 'NInput',
      label: '账户',
      componentProps: {
        placeholder: '请输入账户',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ required: true, message: '请输入账户', trigger: ['blur'] }],
    },
    {
      field: 'phone',
      component: 'NInputNumber',
      label: '手机',
      componentProps: {
        placeholder: '请输入手机号码',
        showButton: false,
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'type',
      component: 'NSelect',
      label: '类型',
      componentProps: {
        placeholder: '请选择类型',
        options: [
          {
            label: '舒适性',
            value: 1,
          },
          {
            label: '经济性',
            value: 2,
          },
        ],
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'status',
      label: '状态',
      //插槽
      slot: 'statusSlot',
    },
  ];
  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });
  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }
  function handleReset(values: Recordable) {
    console.log(values);
  }
  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        window['$message'].success('新建成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      } else {
        window['$message'].error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }
</script>

<style lang="less" scoped></style>
